package com.rh.number.controller;

import com.rh.number.common.ApiResult;
import com.rh.number.common.BatchOperationResult;
import com.rh.number.common.PageResult;
import com.rh.number.dto.*;
import com.rh.number.entity.numberEntity;
import com.rh.number.exception.ClientParseException;
import com.rh.number.exception.EmptyResultException;
import com.rh.number.exception.FileParseException;
import com.rh.number.service.NumberService;
import jakarta.validation.Valid;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * (Number)表控制层
 *
 * @author makejava
 * @since 2025-03-22 10:03:59
 */
@RestController
@RequestMapping(value = "/api/numbers")
public class NumberController {
    private final NumberService numberService;

    public NumberController(NumberService numberService) {
        this.numberService = numberService;
    }

    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public PageResult<numberEntity> queryNumbers(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @ModelAttribute BatchQueryDto batchQuery,
            @ModelAttribute numberEntity condition
    ) {
        // 参数预处理
        if (batchQuery.getNums() != null) {
            try {
                batchQuery.getValidatedNumList();
            } catch (IllegalArgumentException e) {
                return PageResult.error(400, e.getMessage());
            }
        }

        return numberService.selectByCondition(condition, batchQuery, pageNum, pageSize);
    }

    private void validatePagination(int pageNum, int pageSize) {
        if (pageNum < 1) throw new InvalidParameterException("页码必须≥1");
        if (pageSize < 1 || pageSize > 100) {
            throw new InvalidParameterException("每页数量需在1-100之间");
        }
    }

    @PostMapping
    public ApiResult<?> createNumber(
            @Valid @RequestBody numberEntity entity
    ) {
        numberService.insertNumber(entity);
        return ApiResult.success();
    }

    @PostMapping("/bynum")
    public PageResult<numberEntity> batchQueryByNum(
            @RequestParam("file") MultipartFile file,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {

        try {
            // 1. 参数校验
            if (file.isEmpty()) {
                return PageResult.error(400, "文件不能为空");
            }
            if (currentPage < 1 || pageSize < 1) {
                return PageResult.error(400, "分页参数错误");
            }

            // 2. 解析文件并查询数据
            List<numberEntity> allData = numberService.batchQueryByFile(file);
            long totalElements = allData.size();

            // 3. 计算分页
            int totalPages = (int) Math.ceil((double) totalElements / pageSize);
            currentPage = Math.min(currentPage, totalPages); // 防止越界

            // 4. 分页截取数据
            int fromIndex = (currentPage - 1) * pageSize;
            int toIndex = Math.min(fromIndex + pageSize, (int) totalElements);
            List<numberEntity> pagedData = allData.subList(fromIndex, toIndex);

            // 5. 返回分页结果
            return PageResult.success(pagedData, currentPage, pageSize, totalElements, totalPages);

        } catch (IOException e) {
            return PageResult.error(500, "文件处理失败: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return PageResult.error(400, e.getMessage());
        }
    }

    @PostMapping("/batchactivate")  // 批量上架
    public ResponseEntity<PageResult<BatchOperationResult>> batchActivate(
            @RequestParam("file") MultipartFile file) { // 移除 client 参数
        try {
            BatchOperationResult result = numberService.batchActivate(file);
            return ResponseEntity.ok(PageResult.success(
                    Collections.singletonList(result),
                    1, 1,
                    result.getProcessedCount(), 1
            ));
        } catch (FileParseException | ClientParseException e) {
            return ResponseEntity.badRequest().body(
                    PageResult.error(400, e.getMessage())
            );
        } catch (EmptyResultException e) {
            return ResponseEntity.ok().body(
                    PageResult.success(Collections.emptyList(), 1, 1, 0, 0)
            );
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(
                    PageResult.error(500, "系统错误: " + e.getMessage())
            );
        }
    }

    @PostMapping("/batchdeactivate")  // 批量下架
    public ResponseEntity<PageResult<BatchOperationResult>> batchDeactivate(
            @RequestParam("file") MultipartFile file) {

        try {
            BatchOperationResult result = numberService.batchDeactivate(file);
            return ResponseEntity.ok(PageResult.success(
                    Collections.singletonList(result),
                    1, 1,
                    result.getProcessedCount(), 1
            ));
        } catch (FileParseException e) {
            return ResponseEntity.badRequest().body(PageResult.error(400, e.getMessage()));
        } catch (EmptyResultException e) {
            return ResponseEntity.ok().body(PageResult.success(
                    Collections.emptyList(), 1, 1, 0, 0
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(
                    PageResult.error(500, "系统错误: " + e.getMessage())
            );
        }
    }
    //批量编辑

    private Map<String, Object> extractUpdateFields(BatchUpdateRequest request) {
        Map<String, Object> fields = new HashMap<>();
        if (request.getState() != null) fields.put("state", request.getState());
        if (request.getExclusiveStatus() != null) fields.put("exclusiveStatus", request.getExclusiveStatus());
        if (request.getBusinessScenario() != null) fields.put("businessScenario", request.getBusinessScenario());
        if (request.getRemark() != null) fields.put("remark", request.getRemark());
        return fields;
    }
    @PostMapping("/batch-update")
    public ResponseEntity<PageResult<BatchOperationResult>> batchUpdate(
            @Valid @RequestBody BatchUpdateRequest request
    ) {
        try {
            // 直接使用 DTO 中的字段
            BatchOperationResult result = numberService.batchUpdate(
                    request.getIds(),
                    request.getNums(),
                    extractUpdateFields(request)
            );
            return ResponseEntity.ok(PageResult.singleSuccess(result));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(PageResult.error(400, e.getMessage()));
        }
    }


    /**
     * 解析 ID 列表（将 List<?> 转换为 List<Long>）
     */
    private List<Long> parseIds(Object idsParam) {
        if (idsParam == null) return Collections.emptyList();
        return ((List<?>) idsParam).stream()
                .map(id -> {
                    try {
                        return Long.parseLong(id.toString());
                    } catch (NumberFormatException e) {
                        throw new IllegalArgumentException("ID 格式错误: " + id);
                    }
                })
                .collect(Collectors.toList());
    }

    /**
     * 解析号码列表（将 List<?> 转换为 List<String>）
     */
    private List<String> parseNums(Object numsParam) {
        if (numsParam == null) return Collections.emptyList();
        return ((List<?>) numsParam).stream()
                .map(num -> num.toString().trim())
                .collect(Collectors.toList());
    }

    /**
     * 提取更新字段（移除 ids 和 nums）
     */
    private Map<String, Object> extractUpdateFields(Map<String, Object> requestBody) {
        return requestBody.entrySet().stream()
                .filter(entry -> !entry.getKey().equals("ids") && !entry.getKey().equals("nums"))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResult<Void>> updateNumber(
            @PathVariable Long id,
            @RequestBody @Valid OneNumberUpdateDTO dto
    ) {
        numberService.updateNumber(id, dto);
        return ResponseEntity.ok(ApiResult.success(null));
    }

    @DeleteMapping("/delete/{id}")
    public ApiResult<Void> delete(@PathVariable Integer id) {
        return numberService.deleteNumber(id);
    }
    /**
     * 批量删除
     */
    @PostMapping("/delete/batch")
    public ApiResult<Void> batchDelete(@RequestBody IdsRequest request) {
        List<Integer> ids = request.getIds();
        if (ids == null || ids.isEmpty()) {
            return ApiResult.fail(400, "参数不能为空");
        }

        try {
            numberService.batchDeleteNumbers(ids);
            return ApiResult.success();
        } catch (Exception e) {
            return ApiResult.fail(500, "删除失败: " + e.getMessage());
        }
    }

    @PostMapping("/batch-full-update")
    public ResponseEntity<ApiResult<Void>> batchFullUpdate(
            @Valid @RequestBody BatchFullUpdateRequest request
    ) {
        numberService.batchFullUpdate(request.getIds(), request.getUpdateData());
        return ResponseEntity.ok(ApiResult.success());
    }
}